/*公共js*/
/**
 * 确认对话框层，点击确定才真正操作
 * @param msg 对话框的提示文字
 * @param actionUrl 点击确认后请求到的目标 url
 * @param options jquery $.ajax(...) 方法的 options 参数
 */
function confirmAjaxGet(msg, actionUrl, options) {
    layer.confirm(msg, {
        icon: 0
        , title: ''                                      // 设置为空串时，title消失，并自动切换关闭按钮样式，比较好的体验
        , shade: 0.4
        , offset: "139px"
    }, function (index) {                                // 只有点确定后才会回调该方法
        // location.href = operationUrl;                // 操作是一个 GET 链接请求，并非 ajax
        // 替换上面的 location.href 操作，改造成 ajax 请求。后端用 renderJson 更方便，不需要知道 redirect 到哪里
        ajaxGet(actionUrl, options);
        layer.close(index);                             // 需要调用 layer.close(index) 才能关闭对话框
    });
}

/**
 * 删除好友，取消关注，先提醒是否取消关注
 * @param btn    //操作的按钮
 * @param friendId    //用户ID
 */
function deleteFriend(btn, friendId) {
    confirmAjaxGet("取消关注后，此人的动态消息将不会出现在你的首页，确定要操作？", "/my/friendDel?friendId=" + friendId, {
        success: function (ret) {
            if (ret.state == "ok") {
                //setFriendBtn($(btn), friendId, ret.friendRelation);
                var parent = $(btn).parent();
                //var link = "<a class='text-color-999'><i class='icon icon-inbox'></i>私信</a><a href='javascript:void(0);' onclick='handleFriend(this, true, #(user.uid));' class='follow btn btn-normal btn-success' data-original-title='' title='关注他'><span>关注</span><em>|</em></a>";
                var link;
                if (ret.friendRelation == 0) {
                    link = "<a class='text-color-999'><i class='icon icon-inbox'></i>私信</a><a href='javascript:void(0);' onclick='handleFriend(this, true, " + friendId + " );' class='follow btn btn-normal btn-success' data-original-title='' title='添加关注'><span>关注</span><em>|</em></a>";
                } else if (ret.friendRelation == 1) {
                    link = "<a class='text-color-999'><i class='icon icon-inbox'></i>私信</a><a href='javascript:void(0);' onclick='handleFriend(this, false, " + friendId + " );' class='follow btn btn-normal btn-success active' data-original-title='' title='取消关注'><span>取消关注</span><em>|</em></a>";
                } else if (ret.friendRelation == 2) {
                    link = "<a class='text-color-999'><i class='icon icon-inbox'></i>私信</a><a href='javascript:void(0);' onclick='handleFriend(this, true, " + friendId + " );' class='follow btn btn-normal btn-success ' data-original-title='' title='添加关注'><span>您的粉丝</span><em>|</em></a>";
                } else if (ret.friendRelation == 3) {
                    link = "<a class='text-color-999'><i class='icon icon-inbox'></i>私信</a><a href='javascript:void(0);' onclick='handleFriend(this, false, " + friendId + " );' class='follow btn btn-normal btn-success active' data-original-title='' title='取消关注'><span>相互关注</span><em>|</em></a>";
                }
                parent.html(link);
            } else {
                showReplyErrorMsg(ret.msg);
            }
        }
    });
}

/**
 * 关注用户和取消关注用户
 * @param thisBtn    //点击的按钮
 * @param isAdd        //ture关注，false取消关注
 * @param friendId    //关注的用户ID
 */
function handleFriend(thisBtn, isAdd, friendId) {
    var layerIndex = layer.msg("正在加载，请稍后！", {icon: 16, offset: '100px'});
    var url = isAdd;
    //var url = isAdd ? "/my/friendAdd?friendId=" + friendId : "/my/friendDel?friendId=" + friendId;
    if (url != true) {
        deleteFriend(thisBtn, friendId);
    } else {
        url = "/my/friendAdd?friendId=" + friendId;
        ajaxGet(url, {
            success: function (ret) {
                if (ret.state == "ok") {
                    var parent = $(thisBtn).parent();
                    var link;
                    if (ret.friendRelation == 0) {
                        link = "<a class='text-color-999'><i class='icon icon-inbox'></i>私信</a><a href='javascript:void(0);' onclick='handleFriend(this, true, " + friendId + " );' class='follow btn btn-normal btn-success' data-original-title='' title='添加关注'><span>关注</span><em>|</em></a>";
                    } else if (ret.friendRelation == 1) {
                        link = "<a class='text-color-999'><i class='icon icon-inbox'></i>私信</a><a href='javascript:void(0);' onclick='handleFriend(this, false, " + friendId + " );' class='follow btn btn-normal btn-success active' data-original-title='' title='取消关注'><span>已经关注</span><em>|</em></a>";
                    } else if (ret.friendRelation == 2) {
                        link = "<a class='text-color-999'><i class='icon icon-inbox'></i>私信</a><a href='javascript:void(0);' onclick='handleFriend(this, true, " + friendId + " );' class='follow btn btn-normal btn-success ' data-original-title='' title='添加关注'><span>您的粉丝</span><em>|</em></a>";
                    } else if (ret.friendRelation == 3) {
                        link = "<a class='text-color-999'><i class='icon icon-inbox'></i>私信</a><a href='javascript:void(0);' onclick='handleFriend(this, false, " + friendId + " );' class='follow btn btn-normal btn-success active' data-original-title='' title='取消关注'><span>相互关注</span><em>|</em></a>";
                    }
                    parent.html(link);
                } else {
                    showReplyErrorMsg(ret.msg);
                }
            }
            , complete: function (XHR, msg) {
                layer.close(layerIndex);
            }
        });
    }
}

/**
 * 错误弹窗
 * @param msg    弹窗的消息
 */
function showReplyErrorMsg(msg) {
    layer.msg(msg, {
            shift: 6
            , shade: 0.4
            , time: 2000
            // , offset: "140px"
            , closeBtn: 1
            , shadeClose: true
            , maxWidth: "1000"
        }, function () {
        }
    );
}

function sendUserMessage(uid) {
    var url = "/my/sendMessageVerify";
    ajaxGet(url, {
        success: function (ret) {
            //console.log(ret);
            if (ret.state == "ok") {
                //页面层
                layer.open({
                    type: 2,
                    title: "发送私信",
                    area: ['350px', '340px'],
                    content: '/_view/user/sendUserMessage.html?uid=' + uid //iframe的url
                });
            } else {
                showReplyErrorMsg(ret.msg);
            }
        }
        , complete: function (XHR, msg) {
        }
    });
}

/**
 * ajax GET 请求封装，提供了一些默认参数
 */
function ajaxGet(url, options) {
    var defaultOptions = {
        type: "GET"
        , cache: false      // 经测试设置为 false 时，ajax 请求会自动追加一个参数 "&_=nnnnnnnnnnn"
        , dataType: "json"  // "json" "text" "html" "jsonp"，如果设置为"html"，其中的script会被执行
        // , data: {}
        // , timeout: 9000     // 毫秒
        // , beforeSend: function(XHR) {}
        , success: function (ret) {
            if (ret.state == "ok") {
                alert(ret.msg ? ret.msg : "操作成功");
            } else {
                alert("操作失败：" + (ret.msg ? ret.msg : "请告知管理员！"));
            }
        }
        , error: function (XHR, msg) {
            showReplyErrorMsg(msg); // 默认调用
        }
        // , complete: function(XHR, msg){} // 请求成功与失败都调用
    };
    // 用户自定义参数覆盖掉默认参数
    for (var o in options) {
        defaultOptions[o] = options[o];
    }

    $.ajax(url, defaultOptions);
}


/**
 * AJAX提交收藏
 */
function doFavorite(refType, refId, isAdd, options) {
    var url = "/my/favorite/commentsFavoriteAdd?refType=" + refType + "&refId=" + refId;
    if (isAdd != null) {
        url = url + "&isAdd=" + isAdd;
    }
    ajaxGet(url, options);
}

/**
 * 文章收藏和取消收藏
 */
function articleFavorite(refType, refId, isFavoriteAdd, thisBtn) {
    doFavorite(refType, refId, isFavoriteAdd, {
        success: function (ret) {
            if (ret.state == "ok") {
                var parent = $(thisBtn).parent();
                var link;
                var table = '"article"';
                var numbers = Number(document.getElementsByTagName('b')[0].innerHTML);
                if (isFavoriteAdd) {
                    link = "<a href='javascript:;' class='text-color-999' onclick='articleFavorite(" + table + "," + refId + ",false,this);' ><i class='icon icon-favor'></i> <b> " + (numbers + 1) + "</b> 取消收藏</a>";
                } else {
                    link = "<a href='javascript:;' class='text-color-999' onclick='articleFavorite(" + table + "," + refId + ",true,this);' ><i class='icon icon-favor'></i> <b> " + (numbers - 1) + "</b> 收藏</a>";
                }
                parent.html(link);
            } else {
                showReplyErrorMsg(ret.msg);
            }
        }
    });
}

/**
 * 用户个人中心文章取消收藏，这里只有取消收藏，会刷新页面
 */
function myArticleFavorite(refType, refId, isFavoriteAdd, thisBtn) {
    layer.confirm("确认要取消收藏吗？", {
        icon: 0
        , title: ''        // 设置为空串时，title消失，并自动切换关闭按钮样式，比较好的体验
        , shade: 0.4
        , offset: "139px"
    }, function (index) {                  // 只有点确定后才会回调该方法
        doFavorite(refType, refId, isFavoriteAdd, {
            success: function (ret) {
                if (ret.state == "ok") {
                    $(thisBtn).parents(".aw-item").remove();
                } else {
                    showReplyErrorMsg(ret.msg);
                }
            }
        });
        layer.close(index);                 // 需要调用 layer.close(index) 才能关闭对话框
    });
}

/**
 * 话题收藏和取消
 */
function commentsFavorite(refType, refId, isFavoriteAdd, thisBtn) {                            // 只有点确定后才会回调该方法
    doFavorite(refType, refId, isFavoriteAdd, {
        success: function (ret) {
            if (ret.state == "ok") {
                var parent = $(thisBtn).parent();
                var link;
                var table = '"comments"';
                var numbers = Number(document.getElementsByTagName('b')[0].innerHTML);
                if (isFavoriteAdd) {
                    link = "<a href='javascript:;' class='follow btn btn-normal btn-success active' onclick='commentsFavorite(" + table + "," + refId + ",false,this);' data-original-title='' title=''><span>取消关注</span><em>|</em><b>" + (numbers + 1) + "</b></a>";
                } else {
                    link = "<a href='javascript:;' class='follow btn btn-normal btn-success' onclick='commentsFavorite(" + table + "," + refId + ",true,this);' data-original-title='' title=''><span>关注</span><em>|</em><b>" + (numbers - 1) + "</b></a>";
                }
                parent.html(link);
            } else {
                showReplyErrorMsg(ret.msg);
            }
        }
    });
}

/**
 * 用户删除自己的文章
 * @param msg
 * @param operationUrl
 */
function myDeleteArticle(msg, operationUrl) {
    layer.confirm(msg, {
        icon: 0
        , title: ''        // 设置为空串时，title消失，并自动切换关闭按钮样式，比较好的体验
        , shade: 0.4
        , offset: "139px"
    }, function (index) {                  // 只有点确定后才会回调该方法
        location.href = operationUrl;
        layer.close(index);                 // 需要调用 layer.close(index) 才能关闭对话框
    });
}


//share、feedback 详情页回复功能
function articleReply(url, articleId, map) {
    if (map.isLoading) {
        return;
    }

    $.ajax(url, {
        type: "POST"
        , cache: false
        , dataType: "json"
        , data: {
            articleId: articleId,
            replyContent: $('#replyContent').val()
        }
        , beforeSend: function () {
            map.isLoading = true;
            map.submit_btn.hide();
            map.submit_loading.show();
        }
        , success: function (ret) {
            if (ret.state == "ok") {
                var replyContent = $('#replyContent');
                replyContent.val("");
                $(".feed_reply").after(ret.replyItem);
            } else {
                showReplyErrorMsg(ret.msg);
            }
        }
        , complete: function () {
            map.submit_loading.hide();
            map.submit_btn.show();
            map.isLoading = false;
        }
    });
}

//给文章 详情页回复链接的 at 功能
function atAndReply(nickName) {
    var replyContent = $('#replyContent');
    var content = replyContent.val() + "@" + nickName + " ";
    replyContent.val(content);
}

$(document).ready(function () {
    // 自动保存
    var submitted = false, form = $('form[name=write_post],form[name=write_page]').submit(function () {
        submitted = true;
    }), savedData = null;
    // 自动检测离开页
    var lastData = form.serialize();
    $(window).bind('beforeunload', function () {
        if (!!savedData) {
            lastData = savedData;
        }
        if (form.serialize() != lastData && !submitted) {
            return '内容已经改变尚未保存, 您确认要离开此页面吗?';
        }
    });
});
